using System;
using UnityEngine;

namespace ai_library
{
	public class ChangeStateAction<T> : IAction<T> where T : IEntity, IEntityStateMachine<T>
	{
		public ChangeStateAction (StateTypes state, StateTypes globalState)
		{
			State = state;
			GlobalState = globalState;
			Action = ChangeState;
		}

		public Action<T> Action
		{
			get;
			private set;
		}

		public StateTypes State
		{
			get;
			private set;
		}

		public StateTypes GlobalState
		{
			get;
			private set;
		}

		private void ChangeState(T t)
		{
			if (State != StateTypes.NoState)
			{
				IState<T> newCurrentState = StateFactory<T>.Get(State);

				if (newCurrentState == null)
				{
					throw new ActionException("ChangeStateAction: Can't Find State " +
					                          State.ToString());
				}
				else
				{
					if (!t.StateMachine.ChangeCurrentState(newCurrentState))
						throw new ActionException("ChangeStateAction: Failed to change State " +
						                          State.ToString());
				}
			}

			if (GlobalState != StateTypes.NoState)
			{
				IState<T> newGlobalState = StateFactory<T>.Get(GlobalState);
				
				if (newGlobalState == null)
				{
					throw new ActionException("ChangeStateAction: Can't Find GlobalState " +
					                          GlobalState.ToString());
				}
				else
				{
					if (!t.StateMachine.ChangeGlobalState(newGlobalState))
						throw new ActionException("ChangeStateAction: Failed to change GlobalState " +
						                          GlobalState.ToString());
				}
			}
		}
	}
}

